package com.iweb.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/*")
public class SessionFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String servletPath = req.getServletPath();
        String requestURI = req.getRequestURI();

        // 放行静态资源
        if (requestURI.endsWith(".css") ||
                requestURI.endsWith(".js") ||
                requestURI.endsWith(".png") ||
                requestURI.endsWith(".jpg") ||
                requestURI.endsWith(".jpeg") ||
                requestURI.endsWith(".gif") ||
                requestURI.endsWith(".ico")) {
            chain.doFilter(req, res);
            return;
        }
        switch (servletPath) {
            case "/login.User":
            case "/logout.User":
            case "/queryFullName.User":
            case "/login.html":
            case "/addUser.User":
            case"/User/User_toAdd.html":
            case"/checkedusername.User":

                chain.doFilter(req, res);
                break;
            default:
                HttpSession session = req.getSession();
                if (session.getAttribute("user") == null) {
                    res.sendRedirect(req.getContextPath() + "/login.html");
                } else {
                    chain.doFilter(req, res);
                }
                break;
        }
    }
}
